#include"ThreadPool.h"
#include<my_header.h>
#include"cmdtask.h"

#pragma pack(1)
//初始化线程池
int  initThreadPool(ThreadPool *pthreadpool)
{
	printf("start initThreadPool\n");
	pthreadpool->_map = parameterMap();
	if (pthreadpool->_map == NULL) {
		fprintf(stderr, "Failed to load configuration file\n");
		return -1;
	}

	// 打印调试信息
	const char *ip = getKey(pthreadpool->_map, "ip");
	const char *port = getKey(pthreadpool->_map, "port");
	const char *threadNum = getKey(pthreadpool->_map, "threadNum");

	printf("ip: %s\n", ip ? ip : "null");
	printf("port: %s\n", port ? port : "null");
	printf("threadNum: %s\n", threadNum ? threadNum : "null");

	// 检查是否有空值
	if (!ip || !port || !threadNum) {
		fprintf(stderr, "Missing configuration values\n");
		return -1;
	}

	pthread_mutex_init(&pthreadpool->_mThreadLock, NULL);
	pthread_cond_init(&pthreadpool->_mThreadCond, NULL);

	initQueue(&pthreadpool->_queue);
    printf("initQueue DONE\n");

    printf("Malloc SqlConnectPool\n");
    pthreadpool->_sqlPool = (sqlConnectPool *)malloc(sizeof(sqlConnectPool));
    if (!pthreadpool->_sqlPool) {
	    fprintf(stderr, "Failed to allocate memory for sqlPool\n");
	    return -1;
    }
	if(initSqlConnectPool(pthreadpool->_sqlPool, "localhost", "lunisolar",
			   "4164", "netdisk", 10)!=0)
    {
		fprintf(stderr, "Failed to initialize SQL connection pool\n");
		return -1;
    }
    printf("initSqlConnectPool DONE\n");
	pthreadpool->_thread_num = atoi(getKey(pthreadpool->_map, "threadNum"));
	printf("threadNum: %d\n", pthreadpool->_thread_num);
	pthreadpool->_poolThreadId = (pthread_t *)malloc(
		sizeof(pthread_t) * pthreadpool->_thread_num);
	if (pthreadpool->_thread_num <= 0) {
		fprintf(stderr, "Invalid thread number: %s\n",
			getKey(pthreadpool->_map, "threadNum"));
		// 清理资源
		free(pthreadpool->_poolThreadId);
		pthreadpool->_poolThreadId = NULL;
		return -1;
    }
	//创建线程
	for (int i = 0; i < pthreadpool->_thread_num; i++) {
		//子线程需要执行上传下载
		int ret = pthread_create(&pthreadpool->_poolThreadId[i], NULL, threadFunc,
			       pthreadpool);
		if (ret != 0) {
			fprintf(stderr, "Failed to create thread: %s\n",
				strerror(ret));
			// 清理已创建的线程和资源
			for (int j = 0; j < i; j++) {
				pthread_cancel(pthreadpool->_poolThreadId[j]);
			}
			free(pthreadpool->_poolThreadId);
			pthreadpool->_poolThreadId = NULL;
			pthreadpool->_thread_num = 0;
			return -1;
		}
    }
    return 0;
}
//初始化连接
int initTcp(int *sockfd,char *ip,char *port)
{
    printf("start initTcp\n");
	*sockfd = socket(AF_INET, SOCK_STREAM, 0);
	ERROR_CHECK(*sockfd, -1, "SOCKET CREAT ERROR");

    int flag = 1;
    setsockopt(*sockfd,SOL_SOCKET,SO_REUSEADDR,&flag,sizeof(int));
    struct sockaddr_in sockAddr;
    sockAddr.sin_addr.s_addr = inet_addr(ip);
    sockAddr.sin_family = AF_INET;
    sockAddr.sin_port = htons(atoi(port));

    int bind_res = bind(*sockfd,(struct sockaddr*)&sockAddr,sizeof(sockAddr));
    ERROR_CHECK(bind_res, -1, "SOCKET BIND ERROR");

    int listen_res = listen(*sockfd,SOMAXCONN);
    ERROR_CHECK(listen_res, -1, "SOCKET LISTEN ERROR");

    return 0;
}

//添加监听
int epollAdd(int epfd,int fd)
{
    struct epoll_event ev;
    ev.data.fd = fd;
    ev.events = EPOLLIN;
    int epoll_res = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev);
    ERROR_CHECK(epoll_res, -1, "EPOLL ADD ERROR");
    return 0;
}
//删除监听
int epollDel(int epfd,int fd)
{
    struct epoll_event ev;
    ev.data.fd = fd;
    ev.events = EPOLLIN;
    int epoll_res = epoll_ctl(epfd, EPOLL_CTL_DEL, fd, &ev);
    ERROR_CHECK(epoll_res, -1, "EPOLL DEL ERROR");
    return 0;
}

//在这个里面处理客户端的命令
int doRequest(int netfd, ThreadPool *pthreadpool)
{
	int msgLen = 0;
    ssize_t ret =recv(netfd, &msgLen, sizeof(int), MSG_WAITALL);
    printf("msgLen: %d\n", msgLen);
    if (ret<= 0) {
	    printf("CLIENT DISCONNECT\n");
	    close(netfd);
	    return -1;
    }

	//解释发来的协议，解析出命令
    protocol_client client;
    memset(&client, 0, sizeof(protocol_client));
    printf("sizeofclient: %d\n",sizeof(client));
    ret = recv(netfd, &client,msgLen, MSG_WAITALL);
    
    printf("recvData: %s\n",client._data);
    printf("recvCmdType: %d\n",client._cmdType);
    printf("recvNum: %d\n",client._num);
    printf("recvFlag: %d\n", client._flag);
    printf("recvLen: %d\n", client._length);

    int command = client._cmdType;

	//根据命令，选择相应的处理函数
	int res = 0; //返回的类型
	switch (command) {
	case LOGIN:
		loginRequest(netfd, client, pthreadpool);
		break;
	case REGISTER_USERNAME:
		registerNameRequest(netfd, client, pthreadpool);
		break;
	case REGISTER_PASSWORD:
		registerPasswordRequest(netfd, client, pthreadpool);
		break;
    }
    return res;
}

void *threadFunc(void *arg)
{
    printf("threadFunc\n");
}